package client.handle;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import support.EventQueue;
import support.RpcContext;
import support.RpcInfo;
import support.event.SimpleRpcEvent;

import java.util.concurrent.CompletableFuture;

//与注册中心通信的handle
@ChannelHandler.Sharable
public class ClientToCenterInboundHandle extends SimpleChannelInboundHandler<RpcInfo> {
    static Logger logger = LoggerFactory.getLogger(ClientToCenterInboundHandle.class);

    private String flag;

    CompletableFuture<RpcInfo> future;

    public ClientToCenterInboundHandle(String flag) {
        this.flag = flag;
    }

    public CompletableFuture<RpcInfo> getFuture() {
        return future;
    }

    public void setFuture(CompletableFuture<RpcInfo> future) {
        this.future = future;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RpcInfo msg) throws Exception {
        NioSocketChannel channel = (NioSocketChannel) ctx.channel();
        logger.info("注册中心返回结果:{}",msg);
        future.complete(msg);
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        super.channelUnregistered(ctx);
        logger.warn("与注册中心连接丢失，准备准备自动给重连...");
        RpcContext.eventQueue.put(new SimpleRpcEvent(flag));
    }
}
